package zcw.com.lib_leet_code;

/**
 * Created by 朱城委 on 2022/1/27.<br><br>
 *
 * 中等：数字范围按位与
 */
public class Topic201 {

    public static void main(String[] args) {
        BaseSolution solution = new Solution2();

        System.out.println(solution.rangeBitwiseAnd(5, 7));
        System.out.println(solution.rangeBitwiseAnd(0, 0));
        System.out.println(solution.rangeBitwiseAnd(1, 2147483647));
    }

    private interface BaseSolution {
        int rangeBitwiseAnd(int left, int right);
    }

    private static class Solution1 implements BaseSolution {

        @Override
        public int rangeBitwiseAnd(int left, int right) {
            int counter = 0;
            while (left != right) {
                left = left >>> 1;
                right = right >>> 1;
                counter++;
            }

            return left << counter;
        }
    }

    private static class Solution2 implements BaseSolution {

        @Override
        public int rangeBitwiseAnd(int left, int right) {
            while (left < right) {
                right = right & (right - 1);
            }
            return right;
        }
    }
}
